import Vue from "vue"
import Vuex from "vuex"

Vue.use(Vuex)

const state = {
    userId: '',
    userIdentity: '',
    currentCourseId: '',
    currentCourseDetail: null
}

const getters = {
    getUserId: state => {
        return state.userId;
    },
    getUserIdentity: state => {
        return state.userIdentity;
    },
    getCurrentCourseId: state => {
        return state.currentCourseId;
    },
    getCurrentCourseDetail: state => {
        return state.currentCourseDetail;
    }

};

const mutations = {
    setUserId (state, name) {
        state.userId = name;
    },
    setUserIdentity (state, identity) {
        state.userIdentity = identity;
    },
    setCurrentCourseId (state, id) {
        state.currentCourseId = id;
    },
    setCurrentCourseDetail (state, detail) {
        state.currentCourseDetail = detail;
    },
    initFromSessionStorage(state, target) {
        Object.keys(state).forEach(key => {
            if ( target && (typeof(target[key])!=='undefined') ){
                if (key == 'activeElement' || key == 'page' ) return
                state[key] = target[key]
            }
        })
    }
}

const actions = {
}

const plugins = [ store => { //用于持久化state，使刷新页面不丢失
    if ( window.sessionStorage.vuexState ){
        let target = JSON.parse(window.sessionStorage.vuexState)
        store.commit('initFromSessionStorage', target)
    }
    else {
        window.sessionStorage.vuexState = JSON.stringify(store.state)
    }
    store.subscribe((mutation, state) => {
        window.sessionStorage.vuexState = JSON.stringify(state)
    })
}];

const store = new Vuex.Store({
    state,
    getters,
    mutations,
    actions,
    plugins
});

export default store

